package com.design.classroommanagement.util

import com.laughing.lib.utils.Logs.d
import com.laughing.lib.utils.runInBg
import java.sql.*

open class DBUtils {
    companion object {
        @JvmField
        var conn: Connection? = null
        var st: Statement? = null

        @JvmField
        var rs: ResultSet? = null
        var pstmt: PreparedStatement? = null
        var driver = "com.mysql.jdbc.Driver"

        //                    String driver = "com.mysql.cj.jdbc.Driver";
        var url = "jdbc:mysql://192.168.3.161:3306/classroom_management?useUnicode=true&characterEncoding=UTF-8"
        var username = "root"
        var password = "qqqfff"

        @JvmStatic
        val connect: Connection?
            get() {
                runInBg { initConnect() }
                return conn
            }

        suspend fun initConnect(): Connection? {
            if (conn == null) {
                d("initConnect start")
                //加载驱动
                try {
                    Class.forName(driver)
                } catch (e: ClassNotFoundException) {
                    println("加载驱动错误")
                }
                conn = null
                //获取链接
                try {
                    conn = DriverManager.getConnection(url, username, password)
                    d("initConnect ->> conn" + conn)
                } catch (e: SQLException) {
                    e.printStackTrace()
                }
            }
            return conn
        }

        //3. 释放连接资源
        @Throws(Exception::class)
        fun closeAll() {
            try {
                if (rs != null) {
                    rs!!.close()
                    rs = null
                }
                if (st != null) {
                    st!!.close()
                    st = null
                }
                if (conn != null) {
                    conn!!.close()
                    conn = null
                }
                if (pstmt != null) {
                    pstmt!!.close()
                    pstmt = null
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        @Throws(Exception::class)
        fun release(conn: Connection?, prepare: PreparedStatement?) {
            var conn = conn
            var prepare = prepare
            try {
                if (conn != null) {
                    conn.close()
                    conn = null
                }
                if (prepare != null) {
                    prepare.close()
                    prepare = null
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}